package com.sky.financelake.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.sky.financelake.base.BaseA;
import com.sky.financelake.databinding.ActivityPdfViewBinding;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class PdfViewA extends BaseA {

    private ActivityPdfViewBinding binding;
    private static final int PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 100;
    PDFView pdfView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityPdfViewBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        pdfView = binding.pdfView;

        Uri uri = Uri.parse("http://imeitu.oss-cn-beijing.aliyuncs.com/%E7%9F%A5%E8%AF%86%E4%BA%A7%E6%9D%83.pdf");


        if (ActivityCompat.checkSelfPermission(PdfViewA.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(PdfViewA.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(PdfViewA.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
        } else {
            downloadFile();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE:
                downloadFile();
                break;
        }
    }

    private void downloadFile() {
        DownloadFileTask task = new DownloadFileTask(
                PdfViewA.this,
                "http://imeitu.oss-cn-beijing.aliyuncs.com/%E7%9F%A5%E8%AF%86%E4%BA%A7%E6%9D%83.pdf",
                "/download/pdf_file.pdf");
        task.startTask();
    }

    public void onFileDownloaded() {
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/download/pdf_file.pdf");
        if (file.exists()) {
            pdfView.fromFile(file)
                    //.pages(0, 2, 1, 3, 3, 3) // all pages are displayed by default
                    .enableSwipe(true)
                    .swipeHorizontal(true)
                    .enableDoubletap(true)
                    .defaultPage(0)
                    .enableAnnotationRendering(true)
                    .password(null)
                    .scrollHandle(null)
                    .onLoad(new OnLoadCompleteListener() {
                        @Override
                        public void loadComplete(int nbPages) {
                            pdfView.setMinZoom(1f);
                            pdfView.setMidZoom(5f);
                            pdfView.setMaxZoom(10f);
                            pdfView.zoomTo(2f);
                            pdfView.scrollTo(100, 0);
                            pdfView.moveTo(0f, 0f);
                        }
                    })
                    .load();

        }
    }

    public class DownloadFileTask {
        public static final String TAG = "DownloadFileTask";

        private Context context;
        private GetTask contentTask;
        private String url;
        private String fileName;

        public DownloadFileTask(Context context, String url, String fileName) {
            this.context = context;
            this.url = url;
            this.fileName = fileName;
        }

        public void startTask() {
            doRequest();
        }

        private void doRequest() {
            contentTask = new GetTask();
            contentTask.execute();
        }

        private class GetTask extends AsyncTask<String, Integer, String> {

            @Override
            protected String doInBackground(String... arg0) {
                int count;
                try {
                    Log.d(TAG, "url = " + url);
                    URL _url = new URL(url);
                    URLConnection conection = _url.openConnection();
                    conection.connect();
                    InputStream input = new BufferedInputStream(_url.openStream(), 8192);
                    OutputStream output = new FileOutputStream(
                            Environment.getExternalStorageDirectory() + fileName);
                    byte data[] = new byte[1024];
                    while ((count = input.read(data)) != -1) {
                        output.write(data, 0, count);
                    }
                    output.flush();
                    output.close();
                    input.close();
                } catch (Exception e) {
                    Log.e("Error: ", e.getMessage());
                }
                return null;
            }

            protected void onPostExecute(String data) {
                onFileDownloaded();
            }
        }
    }
}
